package com.har.modules.web.controller;

import com.har.common.exception.RRException;
import com.har.common.utils.R;
import com.har.modules.web.entity.LoginEntity;
import com.har.modules.web.entity.UserLoginEntity;
import com.har.modules.web.service.CompanyService;
import com.har.modules.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录
 *
 * @author maorui
 *
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyService companyService;

    /**
     * 企业员工/企业登录
     * @param
     * @return
     */
    @RequestMapping("/login")
    public R Login(@RequestBody LoginEntity loginEntity, HttpServletResponse response) throws Exception {
        UserLoginEntity user=new UserLoginEntity();
        //用户类型 1:企业 0:员工
        if(loginEntity.getType()==0){
            user=userService.selectOne(loginEntity);
            Cookie cookie=new Cookie("type","0");
            cookie.setPath("/");
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
            Cookie cookies = new Cookie("login",user.getToken());
            cookies.setPath("/");
            cookies.setMaxAge(-1);
            response.addCookie(cookie);
            response.addCookie(cookies);

        }
        if(loginEntity.getType()==1){
            user =companyService.selectOne(loginEntity);
            Cookie cookies = new Cookie("login",user.getToken());
            cookies.setPath("/");
            cookies.setMaxAge(-1);
            response.addCookie(cookies);
            Cookie cookie=new Cookie("type","1");
            cookie.setPath("/");
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
        }
        if(null==user){
            throw new RRException("登录失败");
        }


        return R.ok().put("data",user);
    }
    /**
     * 退出
     * @param
     * @return
     */
    @RequestMapping("/loginout")
    public R loginout(HttpServletResponse response){
        //清除cookie
        Cookie cookies = new Cookie("login","");
        cookies.setPath("/");
        cookies.setMaxAge(0);
        response.addCookie(cookies);
        Cookie cookie = new Cookie("type","");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return R.ok();
    }

}
